﻿/// <reference path="../jquery-2.1.0.js" />
$(function () {
    $(document).on('click', '.pax, .gax, .dax', function (e) {
        e.preventDefault();
        var ln = $(this);
        var typeReq = ln.hasClass('gax') ? 'get' : 'post';
        $.ajax({
            url: ln.attr('href'),
            dataType: 'json',
            type: typeReq,
            contentType: 'application/json; charset=utf-8'
        }).done(function (ed) {
            receive(ed, ln);
        });
    });

    $(document).on('click', '.close', function (e) {
        e.preventDefault();
        $($(this).attr('target')).hide();
    });

    $(document).on('click', '.remove', function (e) {
        e.preventDefault();
        $($(this).attr('target')).remove();
    });

    $(document).on('submit', 'form', function (e) {
        e.preventDefault();
        if (!$(this).valid())
            return;
        $(this).ajaxSubmit({
            success: function (ed) {
                receive(ed, null, null);
            }
        });
    });

    $(window).on('popstate', function (e) {
        if (e.state == "ajax")
            window.location.reload();
        else
            window.history.replaceState("ajax", document.title, window.location.href);
        e.preventDefault();
    });

    function receive(ed, ln) {
        if (ed.Redirect) {
            window.location.href = ed.Redirect;
        }
        $(ed.Repl).each(function (i, el) {
            $(el.Select).html(el.Data);
        });
        if (ed.Title && ln && !ln.hasClass('dax')) {
            document.title = ed.Title;
            //if (!ln.hasClass('dax'))
            window.history.pushState("ajax", document.title, ln.attr('href'));
        }
    }
});